//https://leetcode.cn/problems/decode-string/

class Solution {
public:
    string decodeString(string s) {
        stack<string> str;
        stack<int> num;
        str.push("");

        for (int i = 0; i < s.size();)
        {
            if (s[i] >= '0' && s[i] <= '9')
            {
                int nums = 0;
                while (s[i] >= '0' && s[i] <= '9')
                {
                    nums = nums * 10 + (s[i] - '0');
                    i++;
                }
                num.push(nums);
            }
            else if (s[i] == '[')
            {
                i++;
                string temp;
                while (s[i] >= 'a' && s[i] <= 'z')
                {
                    temp += s[i];
                    i++;
                }
                str.push(temp);
            }
            else if (s[i] == ']')
            {
                i++;
                int k = num.top();
                num.pop();
                string t = str.top();
                str.pop();
                while (k--)
                {
                    str.top() += t;
                }

            }
            else
            {
                string temp;
                while (s[i] >= 'a' && s[i] <= 'z')
                {
                    temp += s[i];
                    i++;
                }
                str.top() += temp;

            }
        }

        return str.top();

    }
};